﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class WavePoint : MonoBehaviour {

	protected const float kMinWaveRadius = 0.1f;

	public float waveTime = 2f;
	public float forceAmount = 2f;
	public AnimationCurve forceCurve;

	protected SpriteRenderer _sprite;
	protected Transform _wave;
	protected SpriteRenderer _waveSprite;

	public CircleCollider2D waveCollider { get; protected set; }
	public float maxWaveRadius { get; protected set; }
	public bool waveing { get; protected set; }
	public float waveingTimer { get; protected set; }
	public bool waved { get; protected set; }

	public float GetForce () {
		if (waveing) {
			return forceCurve.Evaluate(Mathf.Clamp01(waveingTimer / waveTime)) * forceAmount;
		} else {
			return 0f;
		}
	}

	public void Reset () {
		if (Application.isPlaying) {
			waveing = false;
			waveingTimer = 0f;
			waveCollider.radius = kMinWaveRadius;
			waved = false;

			_sprite.DOFade(0.5f, 1.5f);
			_waveSprite.enabled = false;
		}
	}

	void Awake () {
		waveCollider = GetComponent<CircleCollider2D>();
		maxWaveRadius = waveCollider.radius;

		_sprite = transform.Find("Sprite").GetComponent<SpriteRenderer>();
		_wave = transform.Find("Wave");
		_waveSprite = _wave.GetComponent<SpriteRenderer>();
		_waveSprite.enabled = false;
	}

	void Update () {
		if (GameController.getInstance().isPlaying) {
			if (waved == false && Input.GetMouseButtonDown(0)) {
				Rect mouseRect = new Rect(new Vector2(transform.position.x - 0.75f, transform.position.y - 0.75f), new Vector2(1.5f, 1.5f));
				Vector3 mouseWorldPosition3D = Camera.main.ScreenToWorldPoint(Input.mousePosition);
				Vector2 mouseWorldPosition2D = new Vector2(mouseWorldPosition3D.x, mouseWorldPosition3D.y);

	//			if (Input.GetMouseButtonUp(0) && waveCollider.OverlapPoint(mouseWorldPosition2D)) {
				if (mouseRect.Contains(mouseWorldPosition2D)) {
					waveing = true;
					waveingTimer = 0f;
					waved = true;

					_sprite.DOFade(0f, 1.5f);
					_waveSprite.enabled = true;

					GameController.getInstance().playSFX(Resources.Load<AudioClip>("Sound/touch_wave"));

					Log(gameObject.name + " WAVEING");
				}
			}
		}
	}

	void FixedUpdate () {
		if (waveing) {
			waveingTimer += Time.fixedDeltaTime;

			if (waveingTimer > waveTime) {
				waveing = false;
				waveCollider.radius = kMinWaveRadius;

				_waveSprite.enabled = false;
			} else {
				waveCollider.radius = Mathf.Lerp(kMinWaveRadius, maxWaveRadius, waveingTimer / waveTime);

				_wave.localScale = new Vector3(waveCollider.radius, waveCollider.radius, 1f);
				_waveSprite.color = new Color(1f, 1f, 1f, Mathf.Clamp01(forceCurve.Evaluate(waveingTimer / waveTime)));
			}
		}
	}

	protected static void Log(string message) {
		Debug.Log("<color=blue>" + message + "</color>");
	}

}
